#!/usr/bin/env python
# -*- coding:utf8 -*-

"""
@version: 
@author: lh
@license: Apache Licence 
@contact: liuhuan0672@gmail.com
@site: 
@software: PyCharm
@file: 0013.py
@time: 2016/1/21 9:25

第 0013 题： 用 Python 写一个爬图片的程序，爬 这个链接里的日本妹子图片 :-)
"""
import os
import re
import urllib.request


def fetch_pics(url):
    html_content = urllib.request.urlopen(url).read()
    print(html_content)
    r = re.compile('<img pic_type="0" class="BDE_Image" src="(.*?)"')
    picture_url_list = r.findall(html_content.decode('utf-8'))

    dir_path = os.path.join(os.getcwd(), 'images')
    if not os.path.exists(dir_path):
        os.mkdir('images')
    os.chdir(dir_path)
    for i in range(len(picture_url_list)):
        picture_name = str(i) + '.jpg'
        try:
            urllib.request.urlretrieve(picture_url_list[i], picture_name)
            print("Success to download " + picture_url_list[i])
        except:
            print("Fail to download " + picture_url_list[i])


if __name__ == '__main__':
    fetch_pics("http://tieba.baidu.com/p/2166231880")
